// @flow
import React, { Component } from 'react'
import styles from './Fault.css'
import { Input, Button, Form } from 'antd'
import FaultGrid from './FaultGrid'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const FormItem = Form.Item

type Props = {
  history: Object,
  form: Object
}
type States = {
  deviceData: Array<any>,
  rowData: Array<Object>,
  total: number,
  current: number,
  pageSize: number
}
class Fault extends Component {
  props: Props
  state: States
  getFaults: Function
  addFault: Function
  handleSearch: Function
  getDeviceData: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      deviceData: [],
      rowData: [],
      total: 0,
      current: 1,
      pageSize: 20
    }
    this.handleSearch = this.handleSearch.bind(this)
    this.getFaults = this.getFaults.bind(this)
    this.addFault = this.addFault.bind(this)
    this.getDeviceData = this.getDeviceData.bind(this)
  }

  handleSearch (e: any) {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log(values)
      }
    })
  }
  componentWillMount () {
    this.getDeviceData()
  }
  getDeviceData () {
    universalFetch(`${__SERVICE_API__}device/devices?pageSize=20000`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        deviceData: json.result
      }, () => {
        this.getFaults(this.state.current, this.state.pageSize)
      })
    })
    .catch((error) => {
      console.error(error)
    })
  }

  getFaults (page: number, pageSize: number) {
    const { deviceData } = this.state
    universalFetch(`${__SERVICE_API__}device/events/faults?pageNum=${page}&pageSize=${pageSize}&order=desc`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          current: page,
          total: json.pageInfo.total,
          rowData: json.result.map((d, i) => {
            const deviceD = deviceData.filter((dd) => dd.id === d.deviceId)
            if (deviceD.length > 0) {
              d['deviceName'] = deviceD[0].name || ''
              d['deviceNo'] = deviceD[0].deviceNo || ''
            }
            return d
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  addFault () {
    this.props.history.push('/business/fault-add')
  }
  render () {
    const { rowData, current, pageSize, total } = this.state
    const { getFieldDecorator } = this.props.form
    return (
      <div className={styles['main']}>
        <div className={styles['action']}>
          <Button type='primary' onClick={this.addFault} style={{ marginTop: '6px' }}>添加故障记录</Button>
          <Form layout='inline' className={styles['tool-bar']}>
            <FormItem>
              {getFieldDecorator('name')(
                <Input placeholder='事件名称' />
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('type')(
                <Input placeholder='事件类型' />
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('prople')(
                <Input placeholder='负责人' />
              )}
            </FormItem>
            <Button icon='search' onClick={this.handleSearch} style={{ marginTop: '2px' }} />
          </Form>
        </div>
        <FaultGrid {...{
          current,
          pageSize,
          total,
          refreshFaults: this.getFaults,
          rowData: rowData,
          history: this.props.history
        }} />
      </div>
    )
  }
}

export default Form.create()(Fault)
